package cn.itsource.org.service.impl;

import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.org.domain.Department;
import cn.itsource.org.mapper.DepartmentMapper;
import cn.itsource.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：部门
 */
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    /**
     * 部门树
     * 思路：
     * 1.将所有的部门查询出来放在Map集合中<id,depertment对象> - 不管
     * 2.遍历所有的部门
     *  如果当前部门没有parent_id = 顶级部门 - 放在部门树
     *  如果当前部门有parent_id = 将当前部门装到父部门的集合中children
     * @return
     */
    @Override
    //配置缓存，redis中的样式 -> dept::tree
    @Cacheable(cacheNames = "dept",key = "'tree'")
    public List<Department> deptTree() {
        /*//查询redis缓存，强转为list
        List<Department> deptTree = (List<Department>) redisTemplate.opsForValue().get("deptTree");
        //判断redis缓存中是否有数据
        if (deptTree == null){
            //调用方法从数据库中查询部门树
            List<Department> tree = getDeptTree();
            //添加到redis缓存中
            redisTemplate.opsForValue().set("deptTree",tree);
            return tree;
        }*/
        return getDeptTree();
    }

    /**
     * 从数据库中查询部门树
     */
    private List<Department> getDeptTree() {
        List<Department> departments = departmentMapper.findAll();
        //将所有的部门查询出来装到Map中，相当于放在内存中，方便等会通过id去取对象
        Map<Long, Department> map = new HashMap<>();
        for (Department department : departments) {
            map.put(department.getId(),department);
        }

        List<Department> deptTree = new ArrayList<>();
        for (Department department : departments) {
            if(department.getParent_id()==null){ //顶级部门
                deptTree.add(department);
            }else{
                //获取父部门的id
                Long parentId = department.getParent_id();
                //获取父部门的对象
                Department parentDepartment = map.get(parentId);
                if(parentDepartment!=null){
                    //将自己状态父部门的集合
                    List<Department> children = parentDepartment.getChildren();
                    children.add(department);
                }
            }
        }
        return deptTree;
    }
}